//
//  CommonViewController.m
//  BGM
//
//  Created by liuqin on 2018/12/7.
//  Copyright © 2018 com.alirtc.demo. All rights reserved.
//

#import "CommonViewController.h"
#import "CommonTableViewCell.h"
#import "Common.h"
#import "BGMUser.h"
#import "BgmInputView.h"
#import "BGMHTTP.h"
#import "SVProgressHUD.h"
#import "MJRefresh.h"
#import "CommonView.h"

@interface CommonViewController ()<UITableViewDelegate,UITableViewDataSource,BgmInputViewDelegate>

@property (nonatomic, strong)UITableView *commonTable;
@property (nonatomic, strong)BgmInputView *inputView;
@property (nonatomic, strong)NSMutableArray *commonArray;

@property (nonatomic, assign)int currentPage;

@end

@implementation CommonViewController





- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navview.hidden = NO;
    self.titleBtn.hidden = NO;
    [self.titleBtn setTitle:@"评论" forState:UIControlStateNormal];
    self.commonArray = [[NSMutableArray alloc]init];
    self.commonTable = [[UITableView alloc]initWithFrame:CGRectMake(0, self.navview.frame.size.height, SCREENW, SCREENH-self.navview.frame.size.height-70)];
    self.commonTable.delegate = self;
    self.commonTable.dataSource = self;
    [self.view addSubview:self.commonTable];
    
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [self.commonTable setTableFooterView:view];
    
    
    
    self.currentPage = 1;
    self.commonTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (self.currentPage ==0) {
            [self.commonTable.mj_header endRefreshing];
        }
         [self requestCommon];
    }];
    
//    self.commonTable.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
//        [self.commonArray removeAllObjects ];
//        self.currentPage = 1;
//
//        self.currentPage = 0;
//        if (self.currentPage==0) {
//            [self.commonTable.mj_header endRefreshing];
//        }else{
//            [self requestCommon];
//        }
//    }];
    
    
    self.inputView = [[BgmInputView alloc]initWithFrame:CGRectMake(0, SCREENH-70, SCREENW, 70)];
    self.inputView.commonDelegate = self;
    [self.view addSubview:self.inputView];
    // 键盘出现的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil];
    // 键盘消失的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHiden:) name:UIKeyboardWillHideNotification object:nil];
    
    [self requestCommon];
    
}



- (void)requestCommon{
    [SVProgressHUD show];
    
    NSDictionary *dic = @{@"userToken":[BGMUser shareInstance].userToken,@"publishId":self.publishId,@"pageNum":[NSString stringWithFormat:@"%d",self.currentPage],@"pageSize":@"10"};
    
    [BGMHTTP requestWithMethodName:@"index/getCommentPublishList" parameters:dic completion:^(BOOL success, NSError *error, NSDictionary *result) {
        NSArray *array = [result objectForKey:@"data"];
        [self reloadCommonView:array ];

        if (array.count==10) {
            self.currentPage = self.currentPage+1;
        }else{
            self.currentPage = 0;
        }
        
        [self.commonTable.mj_header endRefreshing];
        [self.commonTable.mj_footer endRefreshing];

    }];
}
- (void)reloadCommonView:(NSArray *)array{
    dispatch_async(dispatch_get_main_queue(), ^{
 
        for (NSDictionary *dic in array) {
            [self.commonArray insertObject:dic atIndex:0];
        }

        if (self.commonArray.count==0) {
            self.mormalLabel.text = @"暂无评论";
            self.mormalLabel.hidden = NO;
            self.commonTable.hidden = YES;
        }
        [self.commonTable reloadData];
   
    });
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = [self.commonArray objectAtIndex:indexPath.row];
    NSString *str = [NSString stringWithFormat:@"%@",[dic objectForKey:@"content"]];
    return [self getRowHight:str]<70 ? 70 : [self getRowHight:str];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.commonArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identfier = @"CommonTableViewCell";
    CommonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identfier];
    if (cell == nil) {
        cell = [[CommonTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identfier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    NSDictionary *dic = [self.commonArray objectAtIndex:indexPath.row];
    [cell setUserCommonText:dic row:(int)self.commonArray.count -((int)indexPath.row)];
    return cell;
}
#pragma mark -键盘监听方法
- (void)keyboardWasShown:(NSNotification *)notification
{
    // 获取键盘的高度
    CGRect frame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

    
    
//    [UIView animateWithDuration:0.01 animations:^{
        self.inputView.frame = CGRectMake(0, SCREENH-frame.size.height-self.inputView.frame.size.height, SCREENW, self.inputView.frame.size.height);
//    }];
    
    

    
 }
- (void)keyboardWillBeHiden:(NSNotification *)notification
{
    [UIView animateWithDuration:0.1 animations:^{
        self.inputView.frame = CGRectMake(0, SCREENH-self.inputView.frame.size.height, SCREENW, self.inputView.frame.size.height);
    }];
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
-(CGFloat)getRowHight:(NSString *)str{
    UIFont * tfont = [UIFont systemFontOfSize:14];
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:tfont,NSFontAttributeName,nil];
    CGSize  actualsize =[str boundingRectWithSize:CGSizeMake(SCREENW-65, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin  attributes:tdic context:nil].size;
    return actualsize.height+30;
}
-(void)sendCommonText:(NSString *)text{
     [SVProgressHUD show];
    if ([self.userId isEqualToString:[BGMUser shareInstance].userId]) {
        [SVProgressHUD showErrorWithStatus:@"自己不能给自己评论哦"];
        return;
    }
    
   
    NSDictionary *dic = @{@"userToken":[BGMUser shareInstance].userToken,@"publishId":self.publishId,@"content":text,@"userId":[BGMUser shareInstance].userId};
    [BGMHTTP requestWithMethodName:@"index/addComment" parameters:dic completion:^(BOOL success, NSError *error, NSDictionary *result) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.inputView.textView.text = nil;
            NSDictionary *dic = @{@"times":@"刚刚",@"content":text};
            [self reloadTableView:dic];
            self.mormalLabel.hidden = NO;
        });
      
    }];

}

- (void)reloadTableView:(NSDictionary *)dic{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.mormalLabel.hidden = YES;
        self.commonTable.hidden = NO;
        [self.commonArray insertObject:dic atIndex:0];
        [self.commonTable reloadData];
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
        [self.commonTable scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        
        // something
    });
}




@end
